package com.allm.ai.common.factory;

import com.allm.ai.common.entity.AiModel;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

/**
 * ChatModel 工厂
 * 根据 AiModel 的服务提供商动态创建对应的 ChatModel
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class ChatModelFactory {
    
    private final List<ChatModelCreator> creators;
    
    // 创建器缓存，避免每次都遍历查找
    private final Map<String, ChatModelCreator> creatorCache = new ConcurrentHashMap<>();
    
    /**
     * 根据 AiModel 创建 ChatModel
     */
    public ChatModel createChatModel(AiModel aiModel) throws Exception {
        if (aiModel == null) {
            throw new IllegalArgumentException("AiModel 不能为空");
        }
        
        String serviceProvider = normalizeServiceProvider(aiModel.getServiceProvider());
        ChatModelCreator creator = getCreator(serviceProvider);
        
        if (creator == null) {
            throw new UnsupportedOperationException(
                String.format("不支持的服务提供商: %s，可用的提供商: %s", 
                    serviceProvider, getSupportedProviders()));
        }
        
        // 验证配置
        if (!creator.validateConfig(aiModel)) {
            throw new IllegalArgumentException(
                String.format("模型配置验证失败: %s (提供商: %s)", 
                    aiModel.getName(), serviceProvider));
        }
        
        try {
            ChatModel chatModel = creator.createChatModel(aiModel);
            log.info("成功创建 ChatModel: {} (提供商: {})", aiModel.getName(), serviceProvider);
            return chatModel;
        } catch (Exception e) {
            log.error("创建 ChatModel 失败: {} (提供商: {})", aiModel.getName(), serviceProvider, e);
            throw e;
        }
    }
    
    /**
     * 获取创建器
     */
    private ChatModelCreator getCreator(String serviceProvider) {
        return creatorCache.computeIfAbsent(serviceProvider, provider -> {
            for (ChatModelCreator creator : creators) {
                if (provider.equals(normalizeServiceProvider(creator.getServiceProvider()))) {
                    log.debug("找到创建器: {} for {}", creator.getClass().getSimpleName(), provider);
                    return creator;
                }
            }
            log.warn("未找到创建器 for {}", provider);
            return null;
        });
    }
    
    /**
     * 标准化服务提供商名称
     */
    private String normalizeServiceProvider(String serviceProvider) {
        if (serviceProvider == null) {
            return "";
        }
        return serviceProvider.toLowerCase().trim();
    }
    
    /**
     * 检查是否支持指定的服务提供商
     */
    public boolean supportsProvider(String serviceProvider) {
        return getCreator(normalizeServiceProvider(serviceProvider)) != null;
    }
    
    /**
     * 检查模型是否支持流式输出
     */
    public boolean supportsStreaming(AiModel aiModel) {
        String serviceProvider = normalizeServiceProvider(aiModel.getServiceProvider());
        ChatModelCreator creator = getCreator(serviceProvider);
        return creator != null && creator.supportsStreaming();
    }
    
    /**
     * 获取所有支持的服务提供商
     */
    public List<String> getSupportedProviders() {
        return creators.stream()
            .map(ChatModelCreator::getServiceProvider)
            .map(this::normalizeServiceProvider)
            .collect(Collectors.toList());
    }
    
    /**
     * 获取创建器统计信息
     */
    public Map<String, Object> getCreatorStats() {
        Map<String, Object> stats = new ConcurrentHashMap<>();
        stats.put("totalCreators", creators.size());
        stats.put("supportedProviders", getSupportedProviders());
        
        // 每个创建器的详细信息
        Map<String, Object> creatorDetails = creators.stream()
            .collect(Collectors.toMap(
                creator -> creator.getServiceProvider(),
                creator -> Map.of(
                    "className", creator.getClass().getSimpleName(),
                    "supportsStreaming", creator.supportsStreaming()
                )
            ));
        
        stats.put("creatorDetails", creatorDetails);
        stats.put("cacheSize", creatorCache.size());
        
        return stats;
    }
    
    /**
     * 清理创建器缓存
     */
    public void clearCreatorCache() {
        int size = creatorCache.size();
        creatorCache.clear();
        log.info("清理创建器缓存: {} 个条目", size);
    }
} 